package com.mybatisflex.demo.dialect;

import com.mybatisflex.core.dialect.KeywordWrap;
import com.mybatisflex.core.dialect.LimitOffsetProcessor;
import com.mybatisflex.core.dialect.impl.CommonsDialectImpl;
import com.mybatisflex.core.query.CPI;
import com.mybatisflex.core.query.QueryTable;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.query.SqlConnector;
import com.mybatisflex.core.table.TableInfo;
import com.mybatisflex.demo.entity.Account;
import com.mybatisflex.demo.manager.LoginManager;

import static com.mybatisflex.demo.entity.table.AccountTableDef.ACCOUNT;

/**
 * @author 王帅
 * @since 2023-08-14
 */
@SuppressWarnings("all")
public class DataPermissionDialect extends CommonsDialectImpl {

    public DataPermissionDialect() {
        super(KeywordWrap.BACK_QUOTE, LimitOffsetProcessor.MYSQL);
    }

    @Override
    public String buildSelectSql(QueryWrapper queryWrapper) {
        boolean filterTable = CPI.getQueryTables(queryWrapper)
                .stream()
                .map(QueryTable::getName)
                .anyMatch(ACCOUNT.getTableName()::equals);

        if (filterTable) {
            /*QueryCondition condition = CPI.getWhereQueryCondition(queryWrapper);
            while (condition != null) {
                System.out.println(condition.getColumn().getName() + condition.getLogic() + condition.getValue());
                if (condition.getColumn().getName().equals("age")) {
                    condition.when(false);
                }
                condition = CPI.getNextCondition(condition);
            }*/

            Account loginUser = LoginManager.getLoginUser();
            CPI.addWhereQueryCondition(queryWrapper, ACCOUNT.DEPT_ID.eq(loginUser.getDeptId()), SqlConnector.AND);
        }

        return super.buildSelectSql(queryWrapper);
    }

    @Override
    public String buildDeleteSql(QueryWrapper queryWrapper) {
        return super.buildDeleteSql(queryWrapper);
    }

    @Override
    public String forUpdateEntityByQuery(TableInfo tableInfo, Object entity, boolean ignoreNulls, QueryWrapper queryWrapper) {
        return super.forUpdateEntityByQuery(tableInfo, entity, ignoreNulls, queryWrapper);
    }

}